<?php

namespace controller\api;

defined('IA_ROOT') || exit();

use mvc\Controller;
use facade\Model;
use facade\Util;

// 控制器
class Index extends Controller
{
    // 语言
    private $lang = 'zh-CN';
    private $langs = [];
    private $voice = 'cmn-Hans-CN';
    private $localize = [];

    // 系统属性
    private $setting; //系统设置
    private $param; //请求参数
    private $site_url; //站点地址
    private $callback; //JSONP

    // 内容数据
    private $categories = []; //全部分类
    private $tags = []; //全部标签
    private $articles = []; //全部文章
    private $pages = []; //全部页面
    private $users = []; //全部用户数据
    private $comments = []; //全部评论
    private $links = []; //全部友链

    // 初始化
    protected function initialize()
    {
        // 系统属性
        $this->site_url = Util::url(); //站点地址
        $this->param = Util::param(); //请求参数
        $this->callback = isset($this->param['callback']) && $this->param['callback'] && preg_match('/^[a-zA-Z0-9_]+$/', $this->param['callback']) ? $this->param['callback'] : '';
    }

    // 模板赋值
    private function vars()
    {
        $vars = get_class_vars(__CLASS__);
        array_walk($vars, function (&$value, $key) {
            $value = $this->$key;
        });
        return $vars;
    }

    // 私有方法
    private function properties()
    {
        $default = [
            'webLogo' => '/static/images/brand.png',
            'webName' => 'Brand',
            'seo_title' => '',
            'seo_description' => '',
            'upload_type' => 'gif|jpg|jpeg|png|mp3|mp4|zip',
            'upload_size' => '2048',
            'robot_index' => '0',
            'alone_login' => '0',
            'copyright' => '&copy; 2021-' . date('Y') . ' Company, Inc.',
            'icp' => 'ICP No.001',
            'cdn_speed' => '0',
            'slide_image_1' => '',
            'slide_url_1' => '',
            'slide_image_2' => '',
            'slide_url_2' => '',
            'slide_image_3' => '',
            'slide_url_3' => '',
            'slide_image_4' => '',
            'slide_url_4' => '',
            'slide_image_5' => '',
            'slide_url_5' => '',
            'hot_num' => '5',
            'comm_num' => '5',
            'related_num' => '3',
            'page_num' => '24',
            'link_num' => 8,
            'voice_read' => '1',
            'can_comment' => '1',
            'pending_comment' => '1',
            'service' => '',
            // 'email' => '',
            // 'code' => '',
            'static' => '',
            'date' => '',
            'site' => ''
        ];
        $setting = Model::fetch('SELECT * FROM `setting` WHERE id=:id', [':id' => 1]);
        if ($setting) {
            $setting = json_decode($setting['value'], true);
            $setting = array_intersect_key($setting, $default);
            $setting = array_merge($default, $setting);
        } else {
            $setting = $default;
        }
        $this->setting = $setting;
    }

    // 首页
    public function index()
    {
        $this->properties();
        $lang = $this->lang == 'zh-TW' ? 'zh-CN' : $this->lang;

        // 分类数据
        $this->categories = Model::fetchAll("SELECT * FROM `category` WHERE `status` = 0 ORDER BY `id` ASC, `sort` DESC");

        // 标签数据
        $this->tags = Model::fetchAll("SELECT * FROM `tag` WHERE `status` = 0 ORDER BY `sort` DESC, `id` DESC");

        // 文章数据
        $this->articles = Model::fetchAll("SELECT * FROM `article` WHERE `status` = 0 ORDER BY `id` DESC");

        // 页面数据
        $this->pages = Model::fetchAll("SELECT * FROM `page` WHERE `status` = 0 ORDER BY `id` ASC, `sort` DESC");

        // 用户数据
        $this->users = Model::fetchAll("SELECT `id`, `username`, `nickname`, `avatar` FROM `user` WHERE `status` = 0 ORDER BY `id` DESC");

        // 评论数据
        $this->comments = Model::fetchAll("SELECT * FROM `comment` WHERE `status` = 0 ORDER BY `sort` DESC, `id` DESC");

        // 友链数据
        $this->links = Model::fetchAll("SELECT * FROM `link` WHERE `status` = 0  ORDER BY `id` ASC, `sort` DESC");

        // 输出数据
        Util::json(['code' => 0, 'msg' => 'success', 'data' => $this->vars()], $this->callback);
    }

    // 数据转发接口
    public function fetch()
    {
        $param = Util::param();
        $url = isset($param['url']) && $param['url'] ? $param['url'] : '';
        $method = isset($param['method']) && $param['method'] ? strtoupper($param['method']) : 'GET';
        if (isset($param['url'])) unset($param['url']);
        if (isset($param['method'])) unset($param['method']);
        echo Util::curl($url, $param, $method);
    }

    // 谷歌翻译接口
    public function google_translate()
    {
        $param = Util::param(['client', 'dj', 'dt', 'ie', 'oe', 'sl', 'tl', 'tk', 'q']);
        $ipArr = [
            '142.251.43.14', //中国/台湾/台北
            '142.251.220.14', //日本/大阪府/大阪
            '142.251.220.174', //日本/大阪府/大阪
            '142.250.68.46', //美国/加利福尼亚/洛杉矶
            '172.217.12.142', //骨干网
            '172.217.160.110', //骨干网
            '142.251.41.46', //日本/大阪府/大阪
            '142.250.69.206', //美国
            '142.251.222.238', //骨干网
            '172.217.31.142', //骨干网
            '142.251.175.113', //日本/大阪府/大阪
            '172.217.16.238', //西班牙/马德里
            '172.217.24.46', //中国/台湾/台北
            '142.250.71.78', //美国
            '142.251.163.113', //美国/弗吉尼亚/阿什本
            '216.58.215.238', //美国
            '172.217.163.46', //骨干网
            '142.251.132.14', //日本/大阪府/大阪
            '142.251.129.142', //日本/大阪府/大阪
            '192.178.54.78', //美国
        ];
        $ip = $ipArr[array_rand($ipArr)];
        if (!isset($param['q'])) $param['q'] = '';
        $data = array_merge([
            'client' => 'webapp', //参数为gtx不需tk值
            'dj' => '1',
            'dt' => 't',
            'ie' => 'UTF-8',
            'oe' => 'UTF-8',
            'sl' => 'zh-CN',
            'tl' => 'en',
            'tk' => $this->getTk($param['q'])
        ], $param);
        $header = [
            'Content-type: application/x-www-form-urlencoded',
            'X-Requested-With: XMLHttpRequest',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
            'Host: translate.google.com',
            'Referer: https://translate.google.com',
            'X-FORWARDED-FOR: ' . $ip,
            'CLIENT-IP: ' . $ip
        ];
        header('Content-type: application/json; charset=UTF-8');
        header('Access-Control-Allow-Origin: *');
        echo Util::curl('https://translate.google.com/translate_a/single', $data, 'POST', $header);
    }

    // 百度翻译接口
    public function baidu_translate()
    {
        $param = Util::param(['query', 'from', 'to', 'simple_means_flag', 'sign', 'token', 'domain']);
        if (!isset($param['query'])) $param['query'] = '';
        $data = array_merge([
            'from' => 'zh',
            'to' => 'en',
            'simple_means_flag' => '3',
            'sign' => $this->getTk($param['query'], 1),
            'token' => '853eba4bc7ac9601ef8fff761c7cf8cf',
            'domain' => 'common'
        ], $param);
        $header = [
            'Content-type: application/x-www-form-urlencoded',
            'X-Requested-With: XMLHttpRequest',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
            'Referer: https://fanyi.baidu.com',
            'Origin: https://fanyi.baidu.com',
            'Accept: text/event-stream',
            'Cookie: BAIDUID=BBAF98B01ABDC86AE4980FBD0367379A:FG=1'
        ];
        header('Content-type: application/json; charset=UTF-8');
        header('Access-Control-Allow-Origin: *');
        echo Util::curl('https://fanyi.baidu.com/v2transapi', $data, 'POST', $header);
    }

    // 谷歌百度翻译Tk算法（默认谷歌）
    private function getTk($a, $t = 0)
    {
        $gtk = $t ? '320305.131321201' : '406398.2087938574';
        $e = explode('.', $gtk);
        // 转换输入字符串为UTF-16代码单元数组
        $utf16 = mb_convert_encoding($a, 'UTF-16LE', 'UTF-8');
        $codeUnits = array();
        $len = strlen($utf16);
        for ($i = 0; $i < $len; $i += 2) {
            $codeUnit = ord($utf16[$i]) + (ord($utf16[$i + 1]) << 8);
            $codeUnits[] = $codeUnit;
        }
        $g = array();
        $d = 0;
        $f = 0;
        $codeUnitsCount = count($codeUnits);
        while ($f < $codeUnitsCount) {
            $c = $codeUnits[$f];
            if ($c < 0x80) {
                $g[$d++] = $c;
            } elseif ($c < 0x800) {
                $g[$d++] = ($c >> 6) | 0xC0;
                $g[$d++] = ($c & 0x3F) | 0x80;
            } else {
                if (($c & 0xFC00) === 0xD800 && $f + 1 < $codeUnitsCount && ($codeUnits[$f + 1] & 0xFC00) === 0xDC00) {
                    // 处理四字节UTF-8（代理对）
                    $c = 0x10000 + (($c & 0x3FF) << 10) + ($codeUnits[$f + 1] & 0x3FF);
                    $f++;
                    $g[$d++] = ($c >> 18) | 0xF0;
                    $g[$d++] = (($c >> 12) & 0x3F) | 0x80;
                    $g[$d++] = (($c >> 6) & 0x3F) | 0x80;
                    $g[$d++] = ($c & 0x3F) | 0x80;
                } else {
                    // 处理三字节UTF-8
                    $g[$d++] = ($c >> 12) | 0xE0;
                    $g[$d++] = (($c >> 6) & 0x3F) | 0x80;
                    $g[$d++] = ($c & 0x3F) | 0x80;
                }
            }
            $f++;
        }
        $a = $h = (int)$e[0];
        foreach ($g as $val) {
            $a += $val;
            $a &= 0xFFFFFFFF;
            // 处理第一个位运算阶段：'+-a^+6'
            $iStr = '+-a^+6';
            $iStrLength = strlen($iStr);
            for ($k = 0; $k < $iStrLength - 2; $k += 3) {
                $op = $iStr[$k];
                $shiftDir = $iStr[$k + 1];
                $jChar = $iStr[$k + 2];
                $j = ord($jChar) >= ord('a') ? (ord($jChar) - 87) : (int)$jChar;
                $jVal = 0;
                if ($shiftDir === '+') {
                    $jVal = ($a & 0xFFFFFFFF) >> $j;
                } else {
                    $jVal = ($a << $j) & 0xFFFFFFFF;
                }
                if ($op === '+') {
                    $a = ($a + $jVal) & 0xFFFFFFFF;
                } else {
                    $a = ($a ^ $jVal) & 0xFFFFFFFF;
                }
            }
        }
        // 处理第二个位运算阶段：'+-3^+b+-f'
        $iStr2 = '+-3^+b+-f';
        $iStr2Length = strlen($iStr2);
        for ($k = 0; $k < $iStr2Length - 2; $k += 3) {
            $op = $iStr2[$k];
            $shiftDir = $iStr2[$k + 1];
            $jChar = $iStr2[$k + 2];
            $j = ord($jChar) >= ord('a') ? (ord($jChar) - 87) : (int)$jChar;
            $jVal = 0;
            if ($shiftDir === '+') {
                $jVal = ($a & 0xFFFFFFFF) >> $j;
            } else {
                $jVal = ($a << $j) & 0xFFFFFFFF;
            }
            if ($op === '+') {
                $a = ($a + $jVal) & 0xFFFFFFFF;
            } else {
                $a = ($a ^ $jVal) & 0xFFFFFFFF;
            }
        }
        // 异或gtk的第二部分并处理负数
        $a ^= (int)$e[1];
        $a &= 0xFFFFFFFF;
        if ($a < 0) {
            $a = ($a & 0x7FFFFFFF) + 0x80000000;
        }
        // 取模并返回结果
        $a = $a % 1000000;
        return $a . '.' . ($a ^ $h);
    }
}
